import { useEffect } from "react";
import { useStore } from "../../store";
import { observer } from "mobx-react-lite";

const imageTypeRegex = /image\/(png|jpg|jpeg)/gm;

const Import = observer((props: any) => {
    const { resourceStore } = useStore();

    const changeHandler = (e: any) => {
        const { files } = e.target;
        console.log("files", files);
        const validImageFiles = [];
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            if (file.type.match(imageTypeRegex)) {
                validImageFiles.push(file);
            }
        }
        if (validImageFiles.length) {
            resourceStore.clearImage();
            resourceStore.addImage(validImageFiles);
            return;
        }
        alert("Selected images are not of valid type!");
    };

    return (
        <label className="w-5 h-5 hover:cursor-pointer mr-2">
            <svg className="w-5 h-5" fill="#a8a8a8" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <g strokeWidth="0"></g>
                <g strokeLinecap="round" strokeLinejoin="round"></g>
                <g>
                    <polyline points="15 13 11 13 11 9" fill="none" stroke="#a8a8a8" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2">
                    </polyline>
                    <line x1="21" y1="3" x2="11" y2="13"
                        fill="none" stroke="#a8a8a8" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2">
                    </line>
                    <path d="M19,13.89V20a1,1,0,0,1-1,1H4a1,1,0,0,1-1-1V6A1,1,0,0,1,4,5h6.11"
                        fill="none" stroke="#a8a8a8" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2">
                    </path>
                </g>
            </svg>
            <input type='file'
                className="hidden"
                onChange={changeHandler}
                accept="image/png, image/jpg, image/jpeg"
                multiple
            />
        </label>
    );
});

export { Import };
